#!/usr/bin/python
# -*- coding:utf8-*-
"""
导入zb网kline数据
每个小时运行一次
"""

import json

import utils
import sys
import time

TABLE_ZB_TRADE_KILINE = 'zb_trade_data_kline'

MAX_TRI_CNT = 20  # 最大尝试次数


class Exchange_data_import:
    def __init__(self, lis_url, table):
        self.u = utils.CoinTools()
        self.conn = self.u.mysqlconnect()
        self.cur = self.conn.cursor()
        self.lis_url = lis_url
        self.table = table

    def run(self):
        lis = []
        for item in self.lis_url:
            print '======================================'
            print item
            dic = {}
            for try_cnt in xrange(MAX_TRI_CNT):
                try:
                    data = self.u.doGet(item)
                    dic = json.loads(data, encoding='utf8')
                    if dic and dic.has_key('data'):
                        break
                except Exception as e:
                    print e
                    print '重新尝试第' + str(try_cnt + 1) + '次....' + item
                    time.sleep(0.5)
            for i in dic['data']:
                symbol = str(item).split('=')[-1]
                ts = self.u.secondts_2_mints(long(str(i[0])[:-3]))
                open = i[1]
                close = i[4]
                low = i[3]
                high = i[2]
                count = i[5]
                lis.append((ts, symbol, open, close, low, high, count))
            time.sleep(1)
        if lis:
            self.insert(lis)

    def insert(self, lis):
        print lis[0]
        if self.table == TABLE_ZB_TRADE_KILINE:
            sql = """insert into """ + TABLE_ZB_TRADE_KILINE + """ (ts, symbol, open, close, low, high, count) VALUES (%s,%s,%s,%s,%s,%s,%s)"""
            print sql
            self.cur.executemany(sql, lis)
            self.conn.commit()

    def __del__(self):
        self.conn.commit()
        self.cur.close()
        self.conn.close()


def main():
    tool = utils.CoinTools()
    # zb
    lis = ['btc', 'eth', 'bch', 'ltc', 'neo', 'usdt']
    lis_zb_symbol = ['etc_btc', 'ltc_btc', 'eth_usdt', 'ltc_usdt']
    url_zb_rest_api = tool.readini('exchanges_teade_data', 'URL_ZB_REST_API')
    url_zb_kline = tool.readini('exchanges_teade_data', 'URL_ZB_KLINE')
    lis_zb = []
    for item in lis_zb_symbol:
        url = url_zb_rest_api + url_zb_kline + item
        lis_zb.append(url)
    if lis_zb:
        huobi = Exchange_data_import(lis_zb, TABLE_ZB_TRADE_KILINE)
        huobi.run()


if __name__ == '__main__':
    main()
